import * as Cesium from 'cesium';
import BaseDraw from './common/BaseDraw';
import * as CesiumCoord from './common/CesiumCrood';
import * as CesiumCaculater from './common/CesiumCaculater';
import GroupEntityCollection from '../../Common/GroupEntityCollection';
import { v4 } from 'uuid';

/**
 * 派生类-绘制圆形
 *
 */
export default class DrawCircle extends BaseDraw {
    constructor(viewer, tip) {
        super(viewer);
        this.viewer = viewer;
        this.tip = tip; // 提示DOM
        // 事件对象，每种类型的事件只能注册一次
        this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        this.entityCollection = new GroupEntityCollection(viewer); // 集合
        this.ellipsoid = Cesium.Ellipsoid.WGS84;
    }
    // 重置绘制中间量
    resetDraw() {
        this.groupId = v4(); // 当次绘制的-id
        this.labelEntity = null; // 当次绘制的-标签实例
        this.circleEntry = null; // 当次绘制的-圆实例
        this.positionList = []; // 当次绘制的笛卡尔数组
    }
    getAllEntity() {
        return this.entityCollection.getAllEntities();
    }
    // 关闭 CallbackProperty的计算，取最后一次的结果
    removeCallbackProperty() {
        const circleEntry = this.circleEntry;
        const labelEntity = this.labelEntity;
        if (circleEntry) {
            circleEntry.ellipse.semiMinorAxis = circleEntry.ellipse.semiMinorAxis.getValue();
            circleEntry.ellipse.semiMajorAxis = circleEntry.ellipse.semiMajorAxis.getValue();

            // 验证
            // console.log("removeCallbackProperty", {
            //   semiMinorAxis: circleEntry.ellipse.semiMinorAxis,
            //   semiMajorAxis: circleEntry.ellipse.semiMajorAxis,
            // });
        }
        if (labelEntity) {
            labelEntity.label.text = labelEntity.label.text.getValue();
        }
    }
    // 计算半径的 property 属性
    createRadiusProperty() {
        const _this = this;
        const positionList = this.positionList;
        const radiusProperty = new Cesium.CallbackProperty(function () {
            //计算半径 =  两点间距离
            // 1. 笛卡尔坐标转经纬度坐标
            const g1 = CesiumCoord.cartesian3ToLonLatHeight(positionList[0]);
            const g2 = CesiumCoord.cartesian3ToLonLatHeight(positionList[positionList.length - 1]);
            // 2.经纬度坐标转弧度制坐标
            const satrt = Cesium.Cartographic.fromDegrees(g1[0], g1[1]);
            const end = Cesium.Cartographic.fromDegrees(g2[0], g2[1]);
            // 3.计算测地线距离
            const geodesic = new Cesium.EllipsoidGeodesic(satrt, end); // 弧度制坐标
            return geodesic.surfaceDistance; // 获取两点间测地线距离
        }, false);
        return radiusProperty;
    }
    // 生成圆实体
    creatCircleEntity() {
        const _this = this;
        const positionList = this.positionList;
        const cartesian = positionList[positionList.length - 1]; // 最后一个点的笛卡尔坐标
        const radiusProperty = this.createRadiusProperty(); // 半径计算
        const entity = new Cesium.Entity({
            position: _this.positionList[0],
            ellipse: {
                semiMinorAxis: radiusProperty, // 圆形的短轴半径
                semiMajorAxis: radiusProperty, // 圆形的长轴半径
                material: Cesium.Color.YELLOW.withAlpha(0.1),
                outline: true,
                outlineColor: Cesium.Color.RED,
                outlineWidth: 1,
                height: _this.ellipsoid.cartesianToCartographic(cartesian).height,
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
            },
        });
        console.log('圆形实体', entity);
        return entity;
    }
    // 生成标注实体
    creatLabelEntity() {
        const _this = this;
        const positionList = this.positionList;
        const radiusProperty = _this.createRadiusProperty(); // 半径计算
        const entity = new Cesium.Entity({
            position: positionList[0], // 世界坐标
            label: {
                text: new Cesium.CallbackProperty(() => {
                    if (_this.positionList.length > 0) {
                        const r = radiusProperty?.getValue();
                        const area = CesiumCaculater.CircleArea(_this.positionList[0], r); // 计算面积，得到平方米
                        if (area > 1000000) {
                            return '面积:' + (area / 1000000).toFixed(2) + '平方公里';
                        } else {
                            return '面积:' + area.toFixed(2) + '平方米';
                        }
                    } else {
                        return '0';
                    }
                }, false),
                font: '20px',
                color: Cesium.Color.RED,
                pixelOffset: new Cesium.Cartesian2(0, 0),
                fillColor: Cesium.Color.WHITE,
                showBackground: true,
                backgroundColor: Cesium.Color.BLUE,
            },
        });
        return entity;
    }
}

/**
 * 开始绘制点
 * @param {* 是否显示测量Label} showMeasureLabel
 * @param {* 是否连续绘制} continuousDraw
 *
 */
DrawCircle.prototype.startDraw = function (showMeasureLabel = true, continuousDraw = true) {
    const _this = this;
    this.resetDraw(); // 重置绘制中间量
    this.tip.show('单击开始绘制');
    // 左键点击事件
    this.handler.setInputAction(event => {
        const cartesian = CesiumCoord.ScreenToCartesian3(_this.viewer, event.position); // 屏幕坐标转世界坐标
        if (!Cesium.defined(cartesian)) return;
        _this.positionList.push(cartesian.clone());
        // 生成标注
        if (showMeasureLabel && !_this.labelEntity) {
            _this.labelEntity = _this.creatLabelEntity();
            _this.entityCollection.add(_this.labelEntity, _this.groupId);
        }
        // 如果圆实体不存在，开始绘制圆
        if (!_this.circleEntry) {
            _this.circleEntry = _this.creatCircleEntity();
            _this.entityCollection.add(_this.circleEntry, _this.groupId);
            _this.tip.changeText('再次点击结束绘制');
        } else {
            // 点击第二次结束绘制
            this.endDraw();
            if (continuousDraw) {
                // 绘制完后再次绘制
                this.startDraw(showMeasureLabel);
            }
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    // 鼠标移动事件
    this.handler.setInputAction(event => {
        if (_this.circleEntry) {
            const cartesian = CesiumCoord.ScreenToCartesian3(_this.viewer, event.endPosition); // 屏幕坐标转世界坐标
            if (Cesium.defined(cartesian)) {
                const positionList = _this.positionList;
                if (positionList.length === 1) {
                    positionList.push(cartesian.clone());
                } else if (positionList.length >= 2) {
                    positionList.pop();
                    positionList.push(cartesian.clone());
                }
            }
        }
        const { x, y } = event.endPosition;
        _this.tip.moveTipDOMPosition(x, y); // 改变 TipDOM 位置
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    // 右键点击事件
    this.handler.setInputAction(event => {
        this.endDraw();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

/**
 * 结束绘制点
 */
DrawCircle.prototype.endDraw = function () {
    if (this.positionList.length < 3) {
        // 删除这次绘制结果
        this.entityCollection.remove(this.groupId);
    }
    this.tip.close();
    this.removeCallbackProperty(); // 清除 callbackProperty 的执行
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};
/**
 * 清除绘制的点
 */
DrawCircle.prototype.removeDraw = function () {
    this.entityCollection.removeAll();
};
